package com.zb.zeus.gateway.filter;

import com.google.common.base.Stopwatch;
import com.zb.zeus.common.core.constant.CacheConstants;
import com.zb.zeus.common.core.utils.PerfLogger;
import com.zb.zeus.common.core.utils.ServletUtils;
import com.zb.zeus.common.core.utils.StringUtils;
import com.zb.zeus.common.security.context.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * 全局新能日志过滤器
 *
 * @author fujianjian
 * @date 2023/4/11 14:24
 **/
@Slf4j
@Component
public class GlobalPerformanceFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        ServerHttpRequest request = exchange.getRequest();
        String reqUri = request.getURI().getPath();
        String method = request.getMethodValue();
        String hostAddr = request.getRemoteAddress().getAddress().getHostAddress();
        return chain.filter(exchange).doAfterTerminate(() -> {
            String username = exchange.getRequest().getHeaders().getFirst(CacheConstants.DETAILS_USERNAME);
            username = StringUtils.isEmpty(username) ? UserContextHolder.DEFAULT_USER.getAdNum() : ServletUtils.urlDecode(username);
            stopwatch.stop();
            long costMillis = stopwatch.elapsed(TimeUnit.MILLISECONDS);
            PerfLogger.info("{}|{}|{}|{}|{}ms", username, reqUri, method, hostAddr, costMillis);
        });

    }

    @Override
    public int getOrder() {
        return Integer.MIN_VALUE;
    }
}
